﻿using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Xwy.Practical.Utils
{
    public  class QRCodeService
    {
        #region  QRCode

        public  byte[] GetQRCode(string plainText, int pixel)
        {
            var generator = new QRCodeGenerator();
            var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
            var qrCode = new QRCoder.QRCode(qrCodeData);

            var bitmap = qrCode.GetGraphic(pixel);
            var ms = new MemoryStream();
            try
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
            catch (Exception er)
            {
                return null;
            }
            finally {
                bitmap.Dispose();
            }
            
        }

        public  byte[] GetQRCodeWithLogo(string plainText, int pixel, string logoPath)
        {
            var generator = new QRCodeGenerator();
            var qrCodeData = generator.CreateQrCode(plainText, QRCodeGenerator.ECCLevel.Q);
            var qrCode = new QRCoder.QRCode(qrCodeData);

            var bitmap = qrCode.GetGraphic(pixel, Color.Black, Color.White, (Bitmap)Image.FromFile(logoPath), 15, 8);

            var ms = new MemoryStream();
            try
            {
                bitmap.Save(ms, ImageFormat.Jpeg);
                return ms.ToArray();
            }
            catch (Exception er)
            {
                return null;
            }
            finally
            {
                bitmap.Dispose();
            }
        }



        #endregion
    }
}
